import http from '@/api/http'
import type { AxiosRequestConfig } from 'axios'

class HttpService {
  private static instance: HttpService

  // 单例模式
  public static getInstance(): HttpService {
    if (!HttpService.instance) {
      HttpService.instance = new HttpService()
    }
    return HttpService.instance
  }

  /**
   * GET 请求
   * @param url 请求地址
   * @param params 查询参数
   * @param config 额外配置
   */
  public async get<T = any>(url: string, params?: T, config?: AxiosRequestConfig): Promise<T> {
    return http.get(url, { params, ...config })
  }

  /**
   * POST JSON 请求
   * @param url 请求地址
   * @param data JSON 数据
   * @param config 额外配置
   */
  public async postJson<T = any>(url: string, data?: T, config?: AxiosRequestConfig): Promise<T> {
    return http.post(url, data, {
      headers: {
        'Content-Type': 'application/json',
        ...config?.headers,
      },
      ...config,
    })
  }

  /**
   * POST Form 表单请求
   * @param url 请求地址
   * @param data 表单数据
   * @param config 额外配置
   */
  public async postForm<T = any>(url: string, data?: T, config?: AxiosRequestConfig): Promise<T> {
    const formData = new URLSearchParams()
    if (data) {
      Object.keys(data).forEach((key) => {
        formData.append(key, data[key])
      })
    }

    return http.post(url, formData, {
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        ...config?.headers,
      },
      ...config,
    })
  }

  /**
   * 文件下载
   * @param url 下载地址
   * @param filename 保存文件名
   * @param params 查询参数
   */
  public async download(
    url: string,
    filename: string,
    params?: Record<string, any>,
  ): Promise<void> {
    return http
      .get(url, {
        params,
        responseType: 'blob',
      })
      .then((response) => {
        const blob = new Blob([response.data])
        const link = document.createElement('a')
        link.href = URL.createObjectURL(blob)
        link.download = filename
        link.click()
        URL.revokeObjectURL(link.href)
      })
  }

  /**
   * 图片下载
   * @param url 下载地址
   * @param filename 保存文件名
   * @param params 查询参数
   * @description 兼容服务器上资源图片
   */
  public async downloadImage() {}
}

export default HttpService.getInstance()
